/**
 * WebSocket配置工具
 * 统一管理所有WebSocket连接的地址配置
 */

// 获取WebSocket基础URL
export const getWebSocketBaseUrl = (): string => {
  // 1. 优先使用配置文件中的设置
  const globalConfig = (window as any).DEVOPS_CONFIG
  if (globalConfig?.WS_BASE_URL && globalConfig.WS_BASE_URL.trim()) {
    return globalConfig.WS_BASE_URL.trim()
  }

  // 2. 其次使用环境变量配置
  const envWsUrl = import.meta.env.VITE_WS_BASE_URL
  if (envWsUrl && envWsUrl.trim()) {
    return envWsUrl.trim()
  }

  // 3. 根据API地址推导WebSocket地址
  const globalApiConfig = (window as any).DEVOPS_CONFIG
  if (globalApiConfig?.API_BASE_URL && globalApiConfig.API_BASE_URL.trim()) {
    return globalApiConfig.API_BASE_URL.trim().replace(/^http/, 'ws')
  }

  const envApiUrl = import.meta.env.VITE_API_BASE_URL
  if (envApiUrl && envApiUrl.trim()) {
    return envApiUrl.trim().replace(/^http/, 'ws')
  }

  // 4. 同服务器部署：使用当前访问的主机名
  const hostname = window.location.hostname
  const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:'
  return `${protocol}//${hostname}:8000`
}

// 获取完整的WebSocket URL
export const getWebSocketUrl = (path: string, params?: Record<string, string>): string => {
  const baseUrl = getWebSocketBaseUrl()

  // 确保path以/开头
  const normalizedPath = path.startsWith('/') ? path : `/${path}`

  // 构建完整URL
  let fullUrl = `${baseUrl}${normalizedPath}`

  // 添加查询参数
  if (params && Object.keys(params).length > 0) {
    const searchParams = new URLSearchParams(params)
    const separator = fullUrl.includes('?') ? '&' : '?'
    fullUrl += `${separator}${searchParams.toString()}`
  }

  return fullUrl
}

// 获取SSH WebSocket URL
export const getSSHWebSocketUrl = (hostId: number | string, token: string): string => {
  return getWebSocketUrl(`ws/newssh/${hostId}/`, { token })
}

// 获取Docker终端WebSocket URL
export const getDockerTerminalWebSocketUrl = (
  serverId: number | string,
  containerId: string,
  token: string
): string => {
  return getWebSocketUrl(`ws/docker/${serverId}/containers/${containerId}/terminal/`, { token })
}

// 获取Docker日志WebSocket URL
export const getDockerLogsWebSocketUrl = (
  serverId: number | string,
  containerId: string,
  token: string
): string => {
  return getWebSocketUrl(`ws/docker/${serverId}/containers/${containerId}/logs/`, { token })
}

// 获取监控WebSocket URL
export const getMonitoringWebSocketUrl = (token: string): string => {
  return getWebSocketUrl('ws/monitoring/', { auth: token })
}

// 调试信息
export const debugWebSocketConfig = (): void => {
  console.log('🔧 WebSocket配置调试信息:')
  console.log('  配置文件 WS_BASE_URL:', (window as any).DEVOPS_CONFIG?.WS_BASE_URL)
  console.log('  环境变量 VITE_WS_BASE_URL:', import.meta.env.VITE_WS_BASE_URL)
  console.log('  配置文件 API_BASE_URL:', (window as any).DEVOPS_CONFIG?.API_BASE_URL)
  console.log('  环境变量 VITE_API_BASE_URL:', import.meta.env.VITE_API_BASE_URL)
  console.log('  当前主机名:', window.location.hostname)
  console.log('  当前协议:', window.location.protocol)
  console.log('  最终WebSocket基础URL:', getWebSocketBaseUrl())
}
